package com.yx.changdao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yx.changdao.common.entity.Department;
import com.yx.changdao.common.entity.Problem;
import com.yx.changdao.common.entity.ProblemApply;
import com.yx.changdao.common.entity.ProblemInfo;
import com.yx.changdao.common.enums.ApplyType;
import com.yx.changdao.common.enums.Err;
import com.yx.changdao.common.exception.AlertException;
import com.yx.changdao.common.mapper.ProblemApplyMapper;
import com.yx.changdao.common.utils.Faster;
import com.yx.changdao.common.vo.ApplyProblemVO;
import com.yx.changdao.service.DepartmentService;
import com.yx.changdao.service.ProblemApplyService;
import com.yx.changdao.service.ProblemInfoService;
import com.yx.changdao.service.ProblemService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: <br/>
 * 问题申请记录
 * <p>
 * <br/>
 * @Auther: wangzd
 * @create 2020/04/03 16:51
 */
@Service
public class ProblemApplyServiceImpl extends ServiceImpl<ProblemApplyMapper, ProblemApply> implements ProblemApplyService {

    @Autowired
    private ProblemService problemService;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private ProblemInfoService problemInfoService;


    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public boolean agree(Integer applyId,List<Integer> depIds) throws AlertException {
        ProblemApply apply = this.getById(applyId);
        Faster.throwNull(apply, Err.NF_APPLY.n());

        if (!apply.getApplyStatus().equals(0)) {
            throw new AlertException("当前不是提交申请状态");
        }

        apply.setApplyStatus(1);
        updateById(apply); //保存申请

        //主信息
        ProblemInfo problemInfo = problemInfoService.getById(apply.getProblemInfoId());
        Faster.throwNull(problemInfo,Err.NF_PROBLEM.n());

        //已经在处理的部门id集合
        Set<Integer> oldDeptIds = problemService.list(new QueryWrapper<Problem>()
                .select(Problem.DEP_ID)
                .eq(Problem.PROBLEM_INFO_ID, problemInfo.getProblemInfoId()))
                .stream().map(Problem::getDepId).collect(Collectors.toSet());

        //去重
        Set<Integer> depIds_dis = depIds.stream().collect(Collectors.toSet());

        for (Integer depId : depIds_dis) {

            //已经在处理跳过
            if(oldDeptIds.contains(depId)){
                continue;
            }

            Problem problem = new Problem();

            Department department = departmentService.getById(depId);
            Faster.throwNull(department,Err.NF_DEPT.n());

            BeanUtils.copyProperties(problemInfo,problem);

            //擦除不能更新的列
            problemService.advance(problem);

            problem.setSubmitterBy(problemInfo.getCreateBy());
            problem.setSubmitterByName(problemInfo.getCreateByName());
            problem.setSubmitterTime(problemInfo.getCreateTime());

            problem.setIfAssign(1);
            problem.setAssignTime(Faster.now());

            problem.setDepId(department.getDepId());
            problem.setDepName(department.getDepName());

            //更新处理部门名称
            problemInfo.setDepNames(Faster.getStr(problemInfo.getDepNames(), department.getDepName()));

            problemService.save(problem); //保存问题子信息
        }

        //更新问题详情的 疑难件标识
        problemInfo.setIfDifficult(1);
        problemInfoService.updateById(problemInfo); //保存问题详情

        //同步对 主信息（problem_info）和对应所有子信息（problem）打疑难件标识（if_difficult为1）
        problemService.update(new UpdateWrapper<Problem>()
                .set(Problem.IF_DIFFICULT,1)
                .set(Problem.DIFFICULT_STATUS,2)
                .eq(Problem.PROBLEM_INFO_ID,problemInfo.getProblemInfoId()));

        return true;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean agreeBatch(List<Integer> applyIds,List<Integer> depIds) throws AlertException {
        for (Integer id : applyIds) {
            agree(id,depIds);
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean reject(Integer applyId) throws AlertException {

        ProblemApply apply = this.getById(applyId);
        Faster.throwNull(apply, Err.NF_APPLY.n());

        if (!apply.getApplyStatus().equals(0)) {
            throw new AlertException("当前不是提交申请状态");
        }

        problemService.update(new UpdateWrapper<Problem>()
                .set(Problem.DIFFICULT_STATUS,3)
                .eq(Problem.PROBLEM_INFO_ID,apply.getProblemInfoId()));

        apply.setApplyStatus(2);
        return updateById(apply);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean rejectBatch(List<Integer> applyIds) throws AlertException {
        for (Integer id : applyIds) {
            reject(id);
        }
        return true;
    }


    @Override
    public IPage<ApplyProblemVO> pageNex(IPage<ApplyProblemVO> page, QueryWrapper<ApplyProblemVO> queryWrapper) {
        return baseMapper.pageNex(page, queryWrapper);
    }

    @Override
    public ApplyProblemVO byId(Integer id) {
        return baseMapper.byId(id);
    }
}
